from django.shortcuts import render_to_response
from django.views.generic import simple,list_detail,create_update
from django.newforms import form_for_model
from django.template import defaultfilters
from wiki.models import *
from django.http import HttpResponseRedirect
import pprint
from difflib import HtmlDiff
from django.conf import settings

def object_detail(request,slug):
	try:
		page = Page.objects.select_related().get(slug=slug)
		
	except:	
		return simple.redirect_to(request,url='/wiki/add/%s/'%slug)

	return render_to_response('wiki/page_detail.html',{'object':page,'user':request.user,'map_api':settings.GOOGLE_MAP_API_KEY} )


def create_object(request,slug):
	
	if request.POST:
		new_text = Text(text=request.POST.get('current_text','No text'))
		if not request.user.is_anonymous():
			new_text.modify_user = request.user 
			new_text.modify_ip = request.META.get('REMOTE_ADDR','')
		else:
			new_text.modify_ip = request.META.get('REMOTE_ADDR','')
			
		categories = new_text.save()
		new_history = History()
		new_history.save()
		new_history.text_id.add(new_text)
		new_history.save()
		new_page = Page(slug=slug,current_text = new_text,history=new_history,title=request.POST.get('title'))
		
		
		new_page.save()
		
		return simple.redirect_to(request,url='/wiki/show/%s/'%slug)
	else:
		try:
			new_page = Page.objects.get(slug=slug)
			return simple.redirect_to(request,url='/wiki/show/%s/'%slug)
		except:
			return render_to_response('wiki/addpage_form.html',{'user':request.user})
	
def update_object(request,slug):
	TextForm = form_for_model(Text,fields=['modify_comment','text'])
	TextForm.base_fields['text'].widget.attrs = {'cols':60,'rows':30}
	
	if request.POST:
		new_text = Text(text=request.POST.get('text','No text'))
		if not request.user.is_anonymous():
			new_text.modify_user = request.user 
			new_text.modify_ip = request.META.get('REMOTE_ADDR','')
		else:
			new_text.modify_ip = request.META.get('REMOTE_ADDR','')
		
		new_text.modify_comment = request.POST.get('modify_comment','No Comment')
		categories = new_text.save()
		
		new_page = Page.objects.get(slug=slug)
		new_page.history.text_id.add(new_text)
		new_page.current_text = new_text
		
		all_categories = new_page.category.all().values('slug')
		if categories:
			for cat in categories:
				if cat not in all_categories:
					try:
						cat_ob = Category.objects.get(slug=cat)
					except:
						cat_ob = Category(slug=cat,title=cat)
					cat_ob.save()
					new_page.category.add(cat_ob)
		if all_categories:
			for cat1 in all_categories:
				
				if cat1['slug'] not in categories:
					
					try:
						cat_ob1 = Category.objects.get(slug=cat1['slug'])
						new_page.category.remove(cat_ob1)
						
					except:pass
				
					
			
		new_page.save()
		
		return simple.redirect_to(request,url='/wiki/show/%s/'%slug)
	else:
		text = Page.objects.get(slug=slug).current_text
		data = {'text':text.text}
		form = TextForm(data)
		return render_to_response('wiki/page_form.html',{'user':request.user,'form':form})	
	
def history(request,slug,page=1):
	if request.POST:
		Pg = Page.objects.get(slug=slug)
		
		id_1 = request.POST.get('version1')
		id_2 = request.POST.get('version2')
		
		diff = HtmlDiff()
		diff_table = diff.make_table(Text.objects.get(id=id_1).text.splitlines(1),Text.objects.get(id=id_2).text.splitlines(1),str(id_1),str(id_2))
		return render_to_response('wiki/text_diff.html',{'diff_table':diff_table,'object':Pg,'user':request.user})	
	try:
		Pg = Page.objects.get(slug=slug)
		text_history = Pg.history.text_id.all()
		
	except:
		return simple.redirect_to(request,url='/wiki/add/%s/'%slug)

	return list_detail.object_list(request,queryset=text_history,paginate_by=20,extra_context={'object':Pg,'user':request.user},page=page)
def upload (request):
	FileForm = form_for_model(File)
	
	if request.POST:
		data = request.POST.copy()
		data['slug'] =  defaultfilters.slugify(request.FILES['name']['filename'])
		
		form = FileForm(data,request.FILES)
		if form.is_valid():
			form.save()
	else:
		form = FileForm()
	
	
	return render_to_response('wiki/file_form.html',{'form':form,'user':request.user})
	
	
def category(request,slug,page=1):
	try:
		category = Category.objects.get(slug=slug)
		pages = Page.objects.filter(category=category)
	except:
		return simple.redirect_to(request,url='/wiki/category/add/%s/'%slug)
	
	return list_detail.object_list(request,queryset=pages,extra_context={'category':category,'user':request.user},page=page)

def category_add(request,slug=''):
	CategoryForm = form_for_model(Category,fields=('slug','title'))
	if request.POST:
		newpost = request.POST
		post = newpost.copy()
		post['slug'] = defaultfilters.slugify(request.POST['title'])
		form = CategoryForm(post)
		if form.is_valid():
		# Do form processing here...
			form.save()
			try:
				form.save()
			except:
				pass
			return HttpResponseRedirect('/wiki/category/show/%s/'%post['slug'])
	if slug:
		form = CategoryForm({'slug':slug})
	else:
		form = CategoryForm()
		#return create_update.create_object(request,model=Category)
	return render_to_response('wiki/category_form.html',{'form':form,'user':request.user})	
